<?php


namespace app\home\controller;


use app\admin\model\InstrumentBindLogModel;
use app\admin\model\InstrumentModel;
use app\utils\Response;

class InstrumentController extends ApiBase
{
    public function bind()
    {
        $instrumentModel = new InstrumentModel();
        $instrumentBindLogModel = new InstrumentBindLogModel();
        if (!isset($this->requestData['bind_type']) || !in_array($this->requestData['bind_type'], [1, 2])) {
            $this->requestData['bind_type'] = 1;
        }
        // 绑定类型：1绑定，2解绑
        $bindType = (int)$this->requestData['bind_type'];
        // instrument_no 设备编号
        if (!isset($this->requestData['instrument_no']) || trim($this->requestData['instrument_no']) == "") {
            Response::fail("设备编号异常");
        }
        $instrumentNo = trim($this->requestData['instrument_no']);
        $field = ['id', 'title'];
        $instrumentInfo = $instrumentModel->where([
            'status' => 1,
            'is_delete' => 1,
            'title' => $instrumentNo
        ])->field($field)->find();
        if ($bindType == 1) {
            // 记录设备绑定记录
            $instrumentBindLogModel->title = $instrumentNo;
            $instrumentBindLogModel->member_id = $this->memberInfo['id'];
            $instrumentBindLogModel->instrument_id = $instrumentInfo['id'];
            $instrumentBindLogModel->create_time = time();
            $instrumentBindLogModel->save();
            // 修改设备当前绑定人
            $instrumentInfo->current_id = $this->memberInfo['id'];
            $instrumentInfo->save();
        } else {
            // 修改设备当前绑定人
            $instrumentInfo->current_id = 0;
            $instrumentInfo->save();
        }
        Response::success();
    }
}